package com.canaan.business.controller.pc.basic;

import com.canaan.business.domain.basic.WmsStorehouseLocation;
import com.canaan.business.service.basic.IWmsStorehouseLocationService;
import com.canaan.common.annotation.Log;
import com.canaan.common.core.controller.BaseController;
import com.canaan.common.core.domain.AjaxResult;
import com.canaan.common.core.page.TableDataInfo;
import com.canaan.common.enums.BusinessType;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库位Controller
 *
 * @author ruoyi
 * @date 2022-11-29
 */
@Api(tags = "库位管理")
@RestController
@RequestMapping("/basic/location")
public class WmsStorehouseLocationController extends BaseController
{
    @Resource
    private IWmsStorehouseLocationService wmsStorehouseLocationService;

    /**
     * 查询库位列表
     */
    @ApiOperation(value = "查询库位列表")
    @GetMapping("/list")
    public TableDataInfo list(WmsStorehouseLocation wmsStorehouseLocation)
    {
        startPage();
        List<WmsStorehouseLocation> list = wmsStorehouseLocationService.selectWmsStorehouseLocationList(wmsStorehouseLocation);
        return getDataTable(list);
    }
    /**
     * By库位编号获取库位详细信息
     */
    @ApiOperation(value = "By库位编号获取库位详细信息")
    @GetMapping(value = "/locationByNo/{no}")
    public AjaxResult selectWmsStorehouseLocationByNo(@PathVariable("no") String no){
        WmsStorehouseLocation storehouseLocation = wmsStorehouseLocationService.selectWmsStorehouseLocationByNo(no);
        return success(storehouseLocation);
    }

    /**
     * 根据库位获取库区
     * @param nos
     * @return
     */
    @ApiOperation(value = "By库位编号获取库区")
    @GetMapping(value = "/selectAreaByNos")
    public AjaxResult selectAreaByNos(@RequestParam("nos") String nos){
        return success(wmsStorehouseLocationService.listAreaByNos(nos));
    }

    /**
     * By入库规则查询库位列表下拉数据
     */
    @ApiOperation(value = "By入库规则查询库位列表下拉数据")
    @GetMapping(value = "/locationByRule")
    public TableDataInfo selectWmsStorehouseLocationByNo(@RequestParam("storehouseAreaNo") String storehouseAreaNo, @RequestParam("productNo") String productNo){
        List<WmsStorehouseLocation> list = wmsStorehouseLocationService.selectWmsStorehouseLocationList(storehouseAreaNo, productNo);
        return getDataTable(list);
    }

    /**
     * 库位导入模板
     */
    @ApiOperation(value = "库位导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<WmsStorehouseLocation> util = new ExcelUtil<WmsStorehouseLocation>(WmsStorehouseLocation.class);
        util.hideColumn("storehouseAreaName", "storehouseName");
        util.importTemplateExcel(response, "库位数据");
    }

    /**
     * 导入库位列表
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入库位列表")
    @Log(title = "库位", businessType = BusinessType.IMPORT)
    public AjaxResult importExcel(MultipartFile file)
    {
        List<WmsStorehouseLocation> list;
        try {
            //读取excel文件数据
            ExcelUtil<WmsStorehouseLocation> util = new ExcelUtil<WmsStorehouseLocation>(WmsStorehouseLocation.class);
            list = util.importExcel(file.getInputStream());
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("导入文件解析失败");
        }
        //初步校验数据
        if(CollectionUtils.isEmpty(list)){
            throw new ServiceException("文件缺少数据");
        }
        //文件内容的库区必填参数校验
        List<String> nos = list.stream().filter(e -> e.getNo() != null)
                .map(WmsStorehouseLocation::getNo).collect(Collectors.toList());
        List<String> names = list.stream().filter(e -> e.getName() != null)
                .map(WmsStorehouseLocation::getName).collect(Collectors.toList());

        Map<String,List<String>> noListMap = nos.stream().collect(Collectors.groupingBy(e -> e));
        Map<String,List<String>> nameListMap = names.stream().collect(Collectors.groupingBy(e -> e));
        if(noListMap.size() != nos.size()){
            List<String> repetitionList = noListMap.entrySet().stream().filter(e -> e.getValue().size() > 1)
                    .map(Map.Entry::getKey).collect(Collectors.toList());
            throw new ServiceException("文件内库位编号重复：" + repetitionList);
        }else if(nameListMap.size() != names.size()){
            List<String> repetitionList = noListMap.entrySet().stream().filter(e -> e.getValue().size() > 1)
                    .map(Map.Entry::getKey).collect(Collectors.toList());
            throw new ServiceException("文件内库位名称重复：" + repetitionList);
        }

        //深入校验数据和保存数据
        List<String> errorList = wmsStorehouseLocationService.importExcel(list);
        if(!errorList.isEmpty()){
            StringBuilder failureMsg = new StringBuilder();
            failureMsg.append("很抱歉，导入失败！共 ").append(errorList.size()).append(" 条数据格式不正确，错误如下：");
            for (int i = 0; i < errorList.size(); i++) {
                failureMsg.append("<br/>").append(i + 1).append("、").append(errorList.get(i));
            }
            return error(failureMsg.toString());
        }
        return success("导入成功");
    }

    /**
     * 导出库位列表
     */
    @ApiOperation(value = "导出库位列表")
    @Log(title = "库位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsStorehouseLocation wmsStorehouseLocation)
    {
        List<WmsStorehouseLocation> list = wmsStorehouseLocationService.selectWmsStorehouseLocationList(wmsStorehouseLocation);
        ExcelUtil<WmsStorehouseLocation> util = new ExcelUtil<WmsStorehouseLocation>(WmsStorehouseLocation.class);
        util.exportExcel(response, list, "库位数据");
    }

    /**
     * 获取库位详细信息
     */
    @ApiOperation(value = "获取库位详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wmsStorehouseLocationService.selectWmsStorehouseLocationById(id));
    }

    /**
     * 新增库位
     */
    @ApiOperation(value = "新增库位")
    @Log(title = "库位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsStorehouseLocation wmsStorehouseLocation)
    {
        return success(wmsStorehouseLocationService.insertWmsStorehouseLocation(wmsStorehouseLocation));
    }

    /**
     * 修改库位
     */
    @ApiOperation(value = "修改库位")
    @Log(title = "库位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsStorehouseLocation wmsStorehouseLocation)
    {
        return toAjax(wmsStorehouseLocationService.updateWmsStorehouseLocation(wmsStorehouseLocation));
    }

    /**
     * 删除库位
     */
    @ApiOperation(value = "删除库位")
    @Log(title = "库位", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wmsStorehouseLocationService.deleteWmsStorehouseLocationByIds(ids));
    }
}
